package com.woniu.deal.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniu.common.entity.DealOrder;
import com.woniu.common.entity.Result;
import com.woniu.deal.order.feignclient.ElderlyServiceFeign;
import com.woniu.deal.order.service.DealOrderPayService;
import com.woniu.deal.order.service.DealOrderService;
import com.woniu.deal.order.service.DealUseraccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

@RestController
@RequestMapping("/orderDeal")
public class DealOrderDealController {
    @Autowired
    DealOrderService dealOrderService;
    @Autowired
    DealOrderPayService dealOrderPayService;
    @Autowired
    DealUseraccountService dealUseraccountService;
    @Autowired
    ElderlyServiceFeign elderlyServiceFeign;


    //用户支付
    @PostMapping("/{orderNum}")
    //需要seata分布式事务管理
    public Result userPay(@PathVariable("orderNum") String orderNum,HttpServletRequest request) {
        //通过订单编号获取订单信息
        DealOrder order = dealOrderService.getOne(
                new LambdaQueryWrapper<DealOrder>().eq(!StringUtils.isEmpty(orderNum), DealOrder::getOrderNum, orderNum));
        //通过请求头获取用户id(老冉还未写出来)
        System.out.println(order);
        int userId = Integer.parseInt(request.getHeader("userId"));
        Integer code = dealOrderPayService.pay(userId, order);
        if (code == 200) {
            elderlyServiceFeign.serveworkorder_add(order);
            //用户账户扣款
            return Result.ok("支付成功");
        } else if (code == 666) {
            return Result.error("支付失败,账户余额不足，请充值");
        }
        return Result.error("未找到账户，请创建账户");
    }

    //跳转到支付宝支付
    @GetMapping("/{rechargeamout}")
    public Result<String> rechargeToAccout(@PathVariable("rechargeamout")BigDecimal rechargeamout, HttpServletRequest request){
        //从request获取token一起传入带业务层，在业务鞥从token中获取user_id
        String token = request.getHeader("token");
        String form = dealOrderPayService.rechargeCreateOrder(token, rechargeamout);
        return Result.ok(form);
    }

    @PostMapping("/")
    public Result<BigDecimal> getBalance(HttpServletRequest request){
        //通过冉雄给的userId找到账户，把账户里的金额提取出来返回
        BigDecimal balance = dealUseraccountService.selectBalanceById(1);
        return Result.ok(balance);
    }
}
